//
//  LMOrderSearchHistory.m
//  WelfareManager
//
//  Created by longmin on 17/3/23.
//  Copyright © 2017年 timtian. All rights reserved.
//

#import "LMOrderSearchHistory.h"

@implementation LMOrderSearchHistory

@synthesize historyList = _historyList;

- (NSMutableArray *)historyList {
    if (_historyList == nil) {
        _historyList = [NSMutableArray array];
    }
    return _historyList;
}

- (void)setHistoryList:(NSMutableArray *)historyList {
    _historyList = historyList;
    
    [self.historys removeAllObjects];
    
    for (NSString *history in historyList) {
        
        RLMString *his = [[RLMString alloc] init];
        his.rlmStr = history;
        [self.historys addObject:his];
        
    }
}

- (void)addHistory:(NSString *)historyText {
    
    RLMString *rlmText = [[RLMString alloc] initWithValue:historyText];
    
    NSInteger i = 0;
    for (NSString *str in self.historyList) {
        if ([str isEqualToString:historyText]) {
            //包含了添加的文字
            [self.historyList removeObjectAtIndex:i];
            [self.historyList insertObject:str atIndex:0];
            
            [self lm_updateTransactionInBackground:^(RLMObject *updateObj) {
                
                LMOrderSearchHistory *orderSearchHistory = (LMOrderSearchHistory *)updateObj;
                [orderSearchHistory.historys removeObjectAtIndex:i];
                [orderSearchHistory.historys addObject:rlmText];
                
            } complete:nil failed:nil];
            return;
        }
        i++;
    }
    
    if (self.historyList.count < 8) {   //不包含添加的文字
        [self.historyList insertObject:historyText atIndex:0];
        [self.historys insertObject:rlmText atIndex:0];
    }else {
        [self.historyList removeLastObject];
        [self.historyList insertObject:historyText atIndex:0];
        
        [self lm_updateTransactionInBackground:^(RLMObject *updateObj) {
            
            LMOrderSearchHistory *orderSearchHistory = (LMOrderSearchHistory *)updateObj;
            [orderSearchHistory.historys removeLastObject];
            [orderSearchHistory.historys insertObject:rlmText atIndex:0];
            
        } complete:nil failed:nil];
    }
}

+ (instancetype)orderSearchHistory {
    
    LMOrderSearchHistory *history = [LMOrderSearchHistory objectForPrimaryKey:[UserDefaultsHelper getStringForKey:WM_USER_ID]];
    
    if (history == nil) {
        
        history = [[LMOrderSearchHistory alloc] init];
        
    }
    
    return history;
}

+(NSString *)primaryKey {
    return @"user_id";
}

+ (NSDictionary *)defaultPropertyValues {
    return @{
             @"user_id" : [UserDefaultsHelper getStringForKey:WM_USER_ID]
             };
}

+ (NSArray<NSString *> *)ignoredProperties {
    return @[@"historyList"];
}

@end
